<route lang="json5">
{
  style: {
    navigationBarTitleText: '朋友圈'
  }
}
</route>

<script lang="ts" setup>
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { computed, onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'

import { useMomentsStore } from '@/store/moments'
import 'dayjs/locale/zh-cn'

defineOptions({
  name: 'Moments',
})
// 配置 dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const momentsStore = useMomentsStore()
const { success: showSuccess } = useToast()
const commentInputs = ref<Record<string, string>>({})

// 加载状态
// const loading = ref(false)

// 计算相对时间
function getRelativeTime(time: string) {
  return dayjs(time).fromNow()
}

// 预览图片
function previewImage(current: string, urls: string[]) {
  uni.previewImage({
    current,
    urls,
    fail: () => {
      showSuccess('图片加载失败')
    },
  })
}

// 跳转到发布页面
function goToPublish() {
  uni.navigateTo({
    url: '/pages/moments/publish',
  })
}

async function submitComment(momentId: string) {
  const text = (commentInputs.value[momentId] || '').trim()
  if (!text)
    return
  try {
    await momentsStore.addComment(momentId, text)
    commentInputs.value[momentId] = ''
  }
  catch (e) {
    showSuccess('评论失败，请重试')
  }
}

// 获取图片网格样式
function getImageGridClass(count: number) {
  if (count === 1)
    return 'image-grid-single'
  if (count <= 3)
    return 'image-grid-row'
  return 'image-grid-multi'
}

// 下拉刷新
// async function onRefresh() {
//   loading.value = true
//   // 模拟刷新延迟
//   setTimeout(() => {
//     loading.value = false
//     showSuccess('刷新成功')
//   }, 1000)
// }

onMounted(() => {
  const userId = uni.getStorageSync('whoAmI_userId') as string
  if (!userId) {
    setTimeout(() => uni.navigateTo({ url: '/pages/whoami/index' }), 0)
    return
  }
  momentsStore.load().then(() => {
    // 动态加载完成后预取评论
    momentsStore.moments.forEach(m => momentsStore.loadComments(m.id))
  })
})

const moments = computed(() => momentsStore.moments)
</script>

<template>
  <view class="moments-container">
    <!-- 发布按钮 -->
    <view class="publish-btn-container">
      <wd-button type="primary" custom-class="publish-btn" @click="goToPublish">
        <wd-icon name="add" size="16px" />
        发布动态
      </wd-button>
    </view>

    <!-- 动态列表 -->
    <view class="moments-list">
      <view
        v-for="(moment, index) in moments"
        :key="moment.id"
        class="moment-item"
      >
        <!-- 用户信息 -->
        <view class="moment-header">
          <image
            :src="moment.user.avatar"
            class="user-avatar"
            mode="aspectFill"
          />
          <view class="user-info">
            <text class="user-name">{{ moment.user.name }}</text>
            <text class="moment-time">{{ getRelativeTime(moment.createTime) }}</text>
          </view>
        </view>

        <!-- 文字内容 -->
        <view v-if="moment.content" class="moment-content">
          {{ moment.content }}
        </view>

        <!-- 图片网格 -->
        <view
          v-if="moment.images.length > 0"
          class="moment-images"
          :class="getImageGridClass(moment.images.length)"
        >
          <image
            v-for="(image, index) in moment.images"
            :key="index"
            :src="image.url"
            class="moment-image"
            mode="aspectFill"
            @click="previewImage(image.url, moment.images.map(img => img.url))"
          />
        </view>

        <!-- 评论区域 -->
        <view class="comments">
          <view v-for="c in momentsStore.comments[moment.id] || []" :key="c.id" class="comment-item">
            <text class="comment-user">{{ c.userName || c.userId.slice(0, 6) }}</text>
            <text class="comment-content">{{ c.content }}</text>
          </view>
          <view class="comment-input">
            <wd-input v-model="commentInputs[moment.id]" placeholder="写评论…" />
            <wd-button size="small" type="primary" @click="submitComment(moment.id)">
              发送
            </wd-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="moments.length === 0" class="empty-state">
      <wd-icon name="picture" size="64px" color="#ccc" />
      <text class="empty-text">还没有动态，快去发布第一条吧！</text>
    </view>

    <!-- Toast 组件 -->
    <wd-toast />
  </view>
</template>

<style lang="scss" scoped>
.moments-container {
  min-height: 100vh;
  padding-bottom: 40px;
  background: linear-gradient(135deg, #ffb6c1 0%, #ffc0cb 50%, #ffb6c1 100%);
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image:
      radial-gradient(circle at 25% 25%, rgba(255, 182, 193, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, rgba(255, 192, 203, 0.3) 0%, transparent 50%);
    pointer-events: none;
  }
}

.publish-btn-container {
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .publish-btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }
}

.moments-list {
  padding: 0 16px;
}

.moment-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin: 32px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
}

.comments {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;

  .comment-item {
    display: flex;
    gap: 6px;
    margin-bottom: 6px;
    font-size: 13px;
    .comment-user {
      color: #ff6fa1;
      font-weight: 600;
    }
    .comment-content {
      color: #333;
    }
  }

  .comment-input {
    display: flex;
    gap: 8px;
    align-items: center;
    :deep(.wd-input) {
      flex: 1;
    }
  }
}

.moment-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 20px;
    margin-right: 12px;
  }

  .user-info {
    flex: 1;

    .user-name {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .moment-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.moment-content {
  font-size: 15px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 12px;
}

.moment-images {
  display: grid;
  gap: 8px;

  &.image-grid-single {
    grid-template-columns: 1fr;
    max-width: 200px;

    .moment-image {
      width: 100%;
      height: 200px;
    }
  }

  &.image-grid-row {
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    max-width: 300px;

    .moment-image {
      width: 100%;
      height: 100px;
    }
  }

  &.image-grid-multi {
    grid-template-columns: repeat(3, 1fr);

    .moment-image {
      width: 100%;
      height: 100px;
    }
  }
}

.moment-image {
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    transform: scale(1.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;

  .empty-text {
    margin-top: 16px;
    font-size: 14px;
    color: #999;
  }
}
</style>
